import json

from django.contrib.auth import login
from django.shortcuts import render

# Create your views here.
from django_redis import get_redis_connection
from rest_framework import serializers
from rest_framework.generics import GenericAPIView
from rest_framework.mixins import CreateModelMixin
from rest_framework.response import Response

from six_it.models import User
from six_it.serializers import Userserializers


class UsersCreateView(CreateModelMixin,GenericAPIView):
    queryset = User.objects.all()
    serializer_class = Userserializers
    def post(self,request):
        dict = json.loads(request.body)
        mobile = dict['mobile']
        phonecode = dict['phonecode']
        password = dict['password']
        # new_dict = {}
        # new_dict['mobile'] = mobile
        # new_dict['password'] = password
        # new_dict['username'] = mobile
        if not all([mobile,phonecode,password]):
            return Response({
                'errno': '4002',
                'errmsg': '缺少参数'
            })
        conn = get_redis_connection('verify_code')
        mobile_code = conn.get('sms_%s' % mobile)
        if phonecode.lower() != mobile_code.decode().lower():
            return Response({
                'errno':'4002',
                'errmsg':'短信验证码错误'
            })
        try:
            serializers = Userserializers(data=dict)

        except Exception as e:
            return Response({
                'errno': '4001',
                'errmsg': '数据库错误'
            })
        serializers.is_valid(raise_exception=True)

        user = serializers.save()

        login(request, user)
        # request.session['username']
        return Response({
            'errno': '0',
            'errmsg': 'ok'
        })